<template>
  <div class="login-container">
    <!-- 添加粒子效果的canvas -->
    <canvas ref="particleCanvas" class="particle-canvas"></canvas>

    <div class="stars-background">
      <div class="constellation"></div>
    </div>
    <el-form class="login-box" :model="loginForm" :rules="rules" ref="loginFormwrap">
      <h1 class="welcome-text">后台登录界面</h1>
      <div class="login-form">
        <el-form-item class="input-group" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="账号/邮箱"
            prefix-icon="User"
            class="custom-input"
          ></el-input>
        </el-form-item>
        <el-form-item class="input-group" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="输入密码"
            prefix-icon="Lock"
            show-password
            class="custom-input"
          ></el-input>
        </el-form-item>
        <el-button type="primary" class="login-button" @click="handleLogin()"
          >登录</el-button
        >
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, reactive,getCurrentInstance } from "vue";
import {useAllDataStore} from '@/stores/index'
import { useRouter } from "vue-router";
import { User, Lock } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
const { proxy } = getCurrentInstance();
const store=useAllDataStore()
const router = useRouter();
const loginForm = reactive({
  username: "",
  password: "",
});

// const rules = {
//   username: [{ required: true, message: "请输入账号/邮箱", trigger: "blur" }],
//   password: [{ required: true, message: "请输入密码", trigger: "blur" }],
// };
const rules=reactive({
  username: [
    { required: true, message: "请输入账号/邮箱", trigger: "blur" },
  ],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});
const loginFormwrap = ref(null);
const particleCanvas = ref(null);
let animationFrameId = null;

const handleLogin =  () => {
  // 登录逻辑保持不变
  const { username, password } = loginForm;
  loginFormwrap.value.validate(async (valid) => {
   if(valid){
    //  alert('登录成功')
    let reslute = await proxy.$api.getMenu({username, password})
    // 登录成功后拿到菜单数据，然后保存到pinia中,然后渲染菜单数据
    store.state.token=reslute.token
    store.updataMenuList(reslute.menuList)
    store.addMenu(router)
    ElMessage.success("登录成功")
    setTimeout(() => {
      router.push('/home')
    }, 1000);
   }else{
    //  ElMessage.error('请输入正确的账号密码')
    return false
   }
 })

//   console.log("登录请求", username.value, password.value);
//   setTimeout(() => {
//     ElMessage.success("登录成功");
//   }, 1000);
};

onMounted(() => {
  initConstellation();
  initParticles(); // 初始化粒子效果

  // 监听窗口大小变化，调整canvas尺寸
  window.addEventListener("resize", resizeCanvas);
});

onBeforeUnmount(() => {
  // 清理资源
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId);
  }
  window.removeEventListener("resize", resizeCanvas);
});

// 初始化星座动画 (保持原有代码)
function initConstellation() {
  // 原有的星座初始化代码保持不变
  const constellation = document.querySelector(".constellation");
  if (!constellation) return;

  // 创建星座节点和连线
  const nodeCount = 15;
  const nodes = [];

  // 创建节点
  for (let i = 0; i < nodeCount; i++) {
    const node = document.createElement("div");
    node.className = "node";

    const x = Math.random() * 100;
    const y = Math.random() * 100;

    node.style.left = `${x}%`;
    node.style.top = `${y}%`;
    node.style.animationDelay = `${Math.random() * 5}s`;

    constellation.appendChild(node);
    nodes.push({ element: node, x, y });
  }

  // 创建连线
  for (let i = 0; i < nodeCount; i++) {
    const connections = Math.floor(Math.random() * 3) + 1;

    for (let j = 0; j < connections; j++) {
      const targetIndex = Math.floor(Math.random() * nodeCount);
      if (targetIndex !== i) {
        const line = document.createElement("div");
        line.className = "line";

        const node1 = nodes[i];
        const node2 = nodes[targetIndex];

        const dx = node2.x - node1.x;
        const dy = node2.y - node1.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        const angle = (Math.atan2(dy, dx) * 180) / Math.PI;

        line.style.width = `${distance}vw`;
        line.style.left = `${node1.x}%`;
        line.style.top = `${node1.y}%`;
        line.style.transform = `rotate(${angle}deg)`;
        line.style.transformOrigin = "0 0";
        line.style.opacity = `${Math.random() * 0.5 + 0.1}`;

        constellation.appendChild(line);
      }
    }
  }
}

// 粒子系统
function initParticles() {
  const canvas = particleCanvas.value;
  if (!canvas) return;

  const ctx = canvas.getContext("2d");
  let particles = [];

  // 设置canvas尺寸
  function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  }

  resizeCanvas();

  // 粒子类
  class Particle {
    constructor() {
      this.x = Math.random() * canvas.width;
      this.y = Math.random() * canvas.height;
      this.size = Math.random() * 2 + 0.5;
      this.speedX = Math.random() * 0.5 - 0.25;
      this.speedY = Math.random() * 0.5 - 0.25;
      this.color = `rgba(255, 255, 255, ${Math.random() * 0.5 + 0.3})`;
    }

    // 更新粒子位置
    update() {
      this.x += this.speedX;
      this.y += this.speedY;

      // 边界检查
      if (this.x < 0 || this.x > canvas.width) {
        this.speedX = -this.speedX;
      }

      if (this.y < 0 || this.y > canvas.height) {
        this.speedY = -this.speedY;
      }
    }

    // 绘制粒子
    draw() {
      ctx.fillStyle = this.color;
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
      ctx.fill();
    }
  }

  // 创建粒子
  function createParticles() {
    const particleCount = Math.min(
      100,
      Math.floor((canvas.width * canvas.height) / 10000)
    );
    for (let i = 0; i < particleCount; i++) {
      particles.push(new Particle());
    }
  }

  // 绘制粒子和连线
  function drawParticles() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制粒子
    particles.forEach((particle) => {
      particle.update();
      particle.draw();
    });

    // 绘制粒子之间的连线
    for (let i = 0; i < particles.length; i++) {
      for (let j = i + 1; j < particles.length; j++) {
        const dx = particles[i].x - particles[j].x;
        const dy = particles[i].y - particles[j].y;
        const distance = Math.sqrt(dx * dx + dy * dy);

        // 只连接距离较近的粒子
        if (distance < 100) {
          ctx.beginPath();
          ctx.strokeStyle = `rgba(255, 255, 255, ${
            0.1 * (1 - distance / 100)
          })`;
          ctx.lineWidth = 0.5;
          ctx.moveTo(particles[i].x, particles[i].y);
          ctx.lineTo(particles[j].x, particles[j].y);
          ctx.stroke();
        }
      }
    }

    animationFrameId = requestAnimationFrame(drawParticles);
  }

  createParticles();
  drawParticles();
}

// 窗口大小变化时调整canvas尺寸
function resizeCanvas() {
  if (particleCanvas.value) {
    particleCanvas.value.width = window.innerWidth;
    particleCanvas.value.height = window.innerHeight;
  }
}
</script>

<style scoped less>
.login-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;
}

/* 粒子画布样式 */
.particle-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.stars-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, #0b1026 0%, #1a2a52 100%);
  z-index: -1;
  overflow: hidden;
}

/* 其他样式保持不变 */
.stars-background::before,
.stars-background::after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

.stars-background::before {
  background-image: radial-gradient(
      white,
      rgba(255, 255, 255, 0.2) 2px,
      transparent 4px
    ),
    radial-gradient(white, rgba(255, 255, 255, 0.15) 1px, transparent 3px),
    radial-gradient(white, rgba(255, 255, 255, 0.1) 2px, transparent 4px);
  background-size: 550px 550px, 350px 350px, 250px 250px;
  background-position: 0 0, 40px 60px, 130px 270px;
  animation: twinkle 10s linear infinite;
}

.stars-background::after {
  background-image: radial-gradient(
      white,
      rgba(255, 255, 255, 0.15) 1px,
      transparent 2px
    ),
    radial-gradient(white, rgba(255, 255, 255, 0.1) 1px, transparent 2px);
  background-size: 400px 400px, 300px 300px;
  background-position: 50px 150px, 200px 300px;
  animation: twinkle 15s linear infinite;
}

/* 星座动画 */
.constellation {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 0;
}

.node {
  position: absolute;
  width: 4px;
  height: 4px;
  background-color: white;
  border-radius: 50%;
  animation: pulse 3s ease-in-out infinite;
}

.line {
  position: absolute;
  height: 1px;
  background: linear-gradient(
    to right,
    rgba(255, 255, 255, 0.1),
    rgba(255, 255, 255, 0.5),
    rgba(255, 255, 255, 0.1)
  );
  animation: fadeInOut 8s ease-in-out infinite;
}

.login-box {
  width: 400px;
  padding: 20px 0;
  border-radius: 8px;
  background-color: transparent;
  z-index: 2; /* 提高z-index确保在粒子上方 */
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 其余样式保持不变 */
.welcome-text {
  color: #fff;
  text-align: center;
  margin-bottom: 30px;
  font-size: 20px;
  font-weight: normal;
  text-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
  letter-spacing: 1px;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 80%;
}

.input-group .custom-input {
  border-radius: 50px;
  overflow: hidden;
}

.input-group :deep(.el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.1);
  border: none;
  box-shadow: none;
  padding: 0 15px;
  height: 45px;
  border-radius: 50px;
}

.input-group :deep(.el-input__inner) {
  color: #fff;
  height: 45px;
}

.input-group :deep(.el-input__prefix-icon) {
  color: rgba(255, 255, 255, 0.7);
}

.login-button {
  height: 45px;
  font-size: 16px;
  background: #1e88e5;
  border: none;
  margin-top: 10px;
  border-radius: 50px;
  transition: all 0.3s ease;
}

.login-button:hover {
  background: #1976d2;
  box-shadow: 0 0 15px rgba(33, 150, 243, 0.5);
}

@keyframes twinkle {
  0% {
    opacity: 0.5;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.5;
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 0.8;
  }
  50% {
    transform: scale(1.5);
    opacity: 1;
  }
  100% {
    transform: scale(1);
    opacity: 0.8;
  }
}

@keyframes fadeInOut {
  0%,
  100% {
    opacity: 0.1;
  }
  50% {
    opacity: 0.5;
  }
}

/* 树木剪影 */
.login-container::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 20vh;

  background-size: cover;
  background-position: bottom center;
  z-index: 1;
}

.el-form-item {
  margin-bottom: 0px;
}
</style>
